package com.karl.mytask_2.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.karl.mytask_2.R;
import com.karl.mytask_2.bean.MyUser;
import com.karl.mytask_2.bean.Task;
import com.karl.mytask_2.tools.BaseActivity;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Karl on 2016/5/21.
 */
public class TaskInfoActivity extends BaseActivity implements View.OnClickListener {
    private TextView mToolBarTitle;
    private ImageButton mBack;
    private TextView mTitle,mContent,mPrice,mAddress,mName,mPhone;
    private ImageView mImg;
    private Button mBtn;
    private CardView mCard;
    MyUser user;
    String id,title,address,price,content,status,publisher, name, phone,icon;

    //添加图形配置
    ImageOptions mImageOptions = new ImageOptions.Builder().setAutoRotate(true).setCircular(true)
            .setFadeIn(true).setSize(80,80).setLoadingDrawableId(R.mipmap.ic_launcher).build();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.task_info);
        user = BmobUser.getCurrentUser(getApplicationContext(), MyUser.class);
        initView();
        initEvent();

    }
    private void initView(){
        mToolBarTitle = (TextView) findViewById(R.id.tool_bar2_title);
        mBack = (ImageButton) findViewById(R.id.tool_bar2_back);

        mTitle = (TextView) findViewById(R.id.task_info_title);
        mContent = (TextView) findViewById(R.id.task_info_content);
        mPrice = (TextView) findViewById(R.id.task_info_price);
        mAddress = (TextView) findViewById(R.id.task_info_address);

        mName = (TextView) findViewById(R.id.task_info_name);
        mPhone = (TextView) findViewById(R.id.task_info_phone_number);
        mImg = (ImageView) findViewById(R.id.task_info_icon);

        mBtn = (Button) findViewById(R.id.task_info_btn);
        mCard = (CardView) findViewById(R.id.task_info_user);
    }

    private void initEvent(){
        mToolBarTitle.setText("任务详情");
        mBack.setOnClickListener(this);
        mBtn.setOnClickListener(this);
        mPhone.setOnClickListener(this);

        //取出来所有Intent传递的数据
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        title = intent.getStringExtra("title");
        address = intent.getStringExtra("address");
        price = intent.getStringExtra("price");
        content = intent.getStringExtra("content");
        status = intent.getStringExtra("status");
        publisher = intent.getStringExtra("publisher");
        name = intent.getStringExtra("name");
        phone = intent.getStringExtra("phone");
        icon = intent.getStringExtra("icon");

        //将获取到的部分数据显示到界面组件上
        mTitle.setText(title);
        mContent.setText(content);
        mPrice.setText(price);
        mAddress.setText(address);
        mName.setText(name);
        mPhone.setText(phone+"（点击拨打）");

        if (icon == null){
            x.image().bind(mImg,
                    "http://cdnq.duitang.com/uploads/item/201412/27/20141227140012_BV2Bu.jpeg",
                    mImageOptions);
        }else {

            x.image().bind(mImg, icon, mImageOptions);
        }

        setTaskInfoLayout();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tool_bar2_back:
                TaskInfoActivity.this.finish();
                break;
            case R.id.task_info_phone_number:
                Toast.makeText(TaskInfoActivity.this, "点击联系发布者", Toast.LENGTH_SHORT).show();
                break;
            case R.id.task_info_btn:
                Toast.makeText(TaskInfoActivity.this, "提交请求中，请稍等", Toast.LENGTH_SHORT).show();
                clickEvent();
                break;
            default:
                break;
        }
    }



    /**
    * 按钮响应事件
     * 当前用户的任务，
     * 1、status=0，等待接单，点击取消（弹窗警告+删除事件）
     * 2、status=1，等待完成，不可点击
     * 3、status=2，确认完成后付款，可以点击，原本应为支付功能，这里只假设支付成功，直接点击修改status
     * 4、status=3，交易结束
     *
     * 非当前用户
     * 1、status = 0，可接单，点击接单
     * 2、status = 1，进行中，点击完成任务
     * 3、status = 2，等待付款，按钮不可点击
     * 4、status= 3，交易结束
    */
    private void clickEvent(){
        if (isCurrentUser()){
            switch (isStatus()){
                case 0:
                    //删除事件-00
                    setCancel();
                    break;
                case 1:
                    //任务进行中，此时按钮为不可点击状态-01
                    break;
                case 2:
                    //等待付款.这里选择更改状态的方法-02
                    changeStatus("3","付款成功！","付款失败请重新尝试");
                    break;
                case 3:
                    //交易已经结束，不再调用任何方法-03
                    break;
                default:
                    break;
            }
        }else {
            switch (isStatus()){
                case 0:
                    //接单操作-10
                    toQuery("1");
                    break;
                case 1:
                    //任务进行中-11，确认完成，更改status
                    changeStatus("2","完成申请已经成功提交！","出错了！");
                    break;
                case 2:
                    //等待付款-12 等待付款的过程中不可点击,不需要操作

                    break;
                case 3:
                    //交易结束，暂无操作

                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 删除事件-00
     */
    //构造一个弹窗警告！——00_1
    private void setCancel(){
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskInfoActivity.this);
        builder.setTitle("删除任务");
        builder.setMessage("不再等一下吗？");
        builder.setCancelable(false);
        builder.setPositiveButton("确定删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteTask();
            }
        });
        builder.setNegativeButton("好的，不删了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }
    //从云端请求删除数据库中的对应行——00_2
    private void deleteTask(){
        Task task = new Task();
        task.setObjectId(id);
        task.delete(getApplicationContext(), new DeleteListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(TaskInfoActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                TaskInfoActivity.this.finish();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(TaskInfoActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();

            }
        });
    }

    /**
     *更改状态来改变在列表中的显示
     */
    //修改任务数值来显示任务状态。
    private void changeStatus(String status, final String successTxt, final String ErrTxt){
        Task task = new Task();
        task.setStatus(status);
        if (status.equals("1")){
            task.setReceiver(user);
        }
        task.update(getApplicationContext(), id, new UpdateListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(TaskInfoActivity.this, successTxt, Toast.LENGTH_SHORT).show();
                TaskInfoActivity.this.finish();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(TaskInfoActivity.this, ErrTxt, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 当接单的时候调用该方法，类似于事物的处理机制，
     * 每次请求接单都要先查询一下是否已经有人接单，若已经有人抢先接单，
     * 则结束当前活动
     */
    private void toQuery(final String s){
        BmobQuery<Task> query = new BmobQuery<>();
        query.getObject(TaskInfoActivity.this, id, new GetListener<Task>() {
            @Override
            public void onSuccess(Task task) {
                if (task.getReceiver() == null && task.getStatus().equals("0")){
                    changeStatus(s,"接单成功！","接单失败，请检查网络设置后重新尝试");
                }else {
                    Toast.makeText(TaskInfoActivity.this, "已经有人接单了，去看看其他任务吧！", Toast.LENGTH_SHORT).show();
                    TaskInfoActivity.this.finish();
                }

            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(TaskInfoActivity.this, "查询失败，请重新尝试", Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 写布局
     * 1、用户自己的任务的时候：
     * A.当status等于0，待接单，任务栏+取消按钮
     * B.当status等于1,待完成，任务栏+接单人资料+不可选按钮
     * C.当status等于2,待付款，任务栏+接单人资料+付款按钮
     * D.当status等于3，交易结束，只显示任务栏
     *
     * 2、非用户自己的任务
     * A.当status等于0，可接单，任务栏+接单按钮
     * B.当status等于1，进行中，任务栏+发布人资料+完成按钮
     * C.当status等于2，待收款，任务栏+发布人资料+不可选按钮
     * D.当status等于3，交易结束，任务栏
     *
     */
    //布局设置
    private void setTaskInfoLayout(){
        if (isCurrentUser()){
            switch (isStatus()){
                case 0:
                    mBtn.setText("取消任务");
                    mBtn.setClickable(true);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.clickable));
                    mCard.setVisibility(View.GONE);
                    break;
                case 1:
                    mBtn.setText("等待完成");
                    mBtn.setClickable(false);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.clickable));
                    mBtn.setBackgroundColor(getResources().getColor(R.color.unClickable));
                    mCard.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mBtn.setText("确认付款");
                    mBtn.setClickable(true);
                    mCard.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    mBtn.setText("交易已完成");
                    mBtn.setClickable(false);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.unClickable));
                    mCard.setVisibility(View.GONE);
                    break;
            }
        }else{
            switch (isStatus()){
                case 0:
                    mBtn.setText("可接单");
                    mBtn.setClickable(true);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.clickable));
                    mCard.setVisibility(View.GONE);
                    break;
                case 1:
                    mBtn.setText("确认完成");
                    mBtn.setClickable(true);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.clickable));
                    mCard.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mBtn.setText("等待对方付款");
                    mBtn.setClickable(false);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.unClickable));
                    mCard.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    mBtn.setText("交易结束");
                    mBtn.setClickable(false);
                    mBtn.setBackgroundColor(getResources().getColor(R.color.unClickable));
                    mCard.setVisibility(View.GONE);
                    break;
            }
        }
    }
    //判断是否是当前用户的任务，是则返回true，否则返回false
    private boolean isCurrentUser(){
        if (user.getObjectId().equals(publisher)) {
            return true;
        }else {
            return false;
        }
    }
    //根据status状态返回数值
    private int isStatus(){
        if (status.equals("0")){
            return 0;
        }
        if (status.equals("1")){
            return 1;
        }
        if (status.equals("2")){
            return 2;
        }
        return 3;
    }


}
